﻿///////////////////////////////////////////////////////////////////////////////
// 文件名： GraphicsNode.cc
// 作者：   671643387@qq.com
// 日期：   2015年11月1日 下午6:44:36
// 简介：   
///////////////////////////////////////////////////////////////////////////////

#include "graphics/graphics/scenenode/GraphicsNode.hpp"
using namespace ::graphics::graphics::scenenode;

GraphicsNode::GraphicsNode(void)
    : SceneNode(SceneNode::GraphicsNode)
    , scene_(NULL)
    , children_()
{

}

GraphicsNode::~GraphicsNode()
{

}

///////////////////////////////////////////////////////////////////////////////

void GraphicsNode::SetScene(::graphics::graphics::Scene* scene)
{
    scene_ = scene;
    SetScene_(children_);
}

::graphics::graphics::Scene* GraphicsNode::GetScene() const
{
    return scene_;
}

void GraphicsNode::AddChild(GraphicsNodePtr child)
{
    Children::iterator it = children_.begin();
    Children::iterator end = children_.end();
    for (; it != end; ++it)
    {
        if (it->get() == child.get())
            return;
    }
    child->SetScene(GetScene());
    children_.insert(end, child);
}

void GraphicsNode::RemoveChild(GraphicsNode* child)
{
    Children::iterator it = children_.begin();
    Children::iterator end = children_.end();
    for (; it != end; ++it)
    {
        if (it->get() == child)
            break;
    }
    if (it != end)
    {
        child->SetScene(NULL);
        children_.erase(it);
    }
}

void GraphicsNode::Render()
{
    // IF HAS MESH, RENDER IT
    ::graphics::ComponentPtr meshRender = GetComponent(std::string("MeshRender"));
    if (meshRender)
    {
        meshRender->Render();
    }

    // RENDER CHILDREN
    Children::iterator it = children_.begin();
    Children::iterator end = children_.end();
    for (; it != end; ++it)
    {
        (*it)->Render();
    }
}

///////////////////////////////////////////////////////////////////////////////

void GraphicsNode::SetScene_(Children& children)
{
    if (children_.empty())
        return;

    Children::iterator it = children_.begin();
    Children::iterator end = children_.end();
    for (; it != end; ++it)
    {
        (*it)->SetScene(scene_);
    }
}